package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.activity.SplashActivity;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.AppUtils;
import com.zhongshengnetwork.rightbe.common.ChildViewPager;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TextUtil.DisplayUtils;
import com.zhongshengnetwork.rightbe.common.WidgetController;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.TransparentBaseActivity;
import com.zhongshengnetwork.rightbe.common.card.view.HorizontalInnerViewPager;
import com.zhongshengnetwork.rightbe.common.card.view.HorizontalViewPager;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.KeyMapDailog;
import com.zhongshengnetwork.rightbe.common.love.Love;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.CommentdbModel;
import com.zhongshengnetwork.rightbe.dbservice.CommentdbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuContentDetailModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuInfoDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangCommentActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.lang.model.CardViewAdapter;
import com.zhongshengnetwork.rightbe.lang.model.ScaleTransformer;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.WZTCardAdapter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

//import cn.jiguang.analytics.android.api.JAnalyticsInterface;

import static com.huantansheng.easyphotos.constant.Code.REQUEST_PERMISSION;

public class WZTCardActivity extends AppCompatActivity {

    private WeiShuInfoDetailModel weiShuInfoDetailModel;

    private boolean isLastPage = false;
    private boolean isDragPage = false;
    private boolean canJumpPage = false;
    private boolean isHasMore = true;
    private boolean isShowNoMore = false;

    private static final int Records = 20;
    private int pageIndex = 0;
    private static final int maxReadCount = 11;
    private int totalCount = 0;

    private WZTCardAdapter adapter;
    private ViewPager viewPager;
    //加载动画
    private AVLoadingIndicatorView avi;

    private RelativeLayout banner_back_layout;
    private RelativeLayout banner_more_layout;
    private ImageView cardview_bg_img;
    private TextView card_page;
    private ImageView lang_member_icon;
    private ImageView card_page_header;
    private TextView card_all_page;
    public Love love_layout;
    private boolean isHasPic = false;
    private boolean isShowCare = false;
    private boolean hasShowNoMore = false;

    private boolean showLove = false;

    private ImageView music_icon;

    //动态评论
    private RelativeLayout comment_one;
    private ImageView comment_one_header;
    private TextView comment_one_text;

    private RelativeLayout comment_two;
    private ImageView comment_two_header;
    private TextView comment_two_text;

    private RelativeLayout comment_three;
    private ImageView comment_three_header;
    private TextView comment_three_text;

    private int gas = 0;
    private int bottomY = 0;
    private int layoutHeight;
    private boolean isFirstMove = false;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private MyHandler mHandler = null;
    private static int delay = 2500;  //2.5s
    private static int period = 2500;  //2.5s

    //数据操作
    private HashMap<String, Integer> displayIndexMap;//显示的下标，key是index
    private HashMap<String, String> dataMap; //记录是否获取过数据，key是index
    private HashMap<String, String> dataIndexMap; //记录数据的下标，key是wj+langid
    private List<DryCommentModel> dataList;//当前数据
    private static int lastIndex = 0;
    private DryCommentModel a;
    private DryCommentModel b;
    private DryCommentModel c;

    //评论弹出框
    private KeyMapDailog dialog = null;


    static class MyHandler extends Handler {

        WeakReference<WZTCardActivity> mWeakReference;
        public MyHandler(WZTCardActivity activity)
        {
            mWeakReference=new WeakReference<WZTCardActivity>(activity);
        }

        //子类重写次方法，处理消息

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(mWeakReference == null){
                return;
            }
            final WZTCardActivity activity = mWeakReference.get();
            if (activity == null){
                return;
            }
            if (msg == null){
                return;
            }
            if (msg.what > 0){
                if (activity.isFirstMove == false){
                    activity.displayComment();
                }
            }
        }
    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(1);
                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            mTimer.schedule(mTimerTask, delay, period);
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    private void initMoveComment(){

        new Thread(){
            @Override
            public void run() {
                super.run();
                CommentdbService.deleteData();
            }
        }.start();

        displayIndexMap = new HashMap<String, Integer>();
        dataMap = new HashMap<String, String>();
        dataIndexMap = new HashMap<String, String>();
        dataList = new ArrayList<DryCommentModel>();
        lastIndex = 0;
        a = null;
        b = null;
        c = null;

        int w = ScreenUtils.getScreenWidth(WZTCardActivity.this);
        int imgH = Math.round(w / Configs.Value.IMAGE_WIDTH_HEIGHT_RATIO);
        bottomY = imgH + DisplayUtils.dp2px(WZTCardActivity.this, 40);
        layoutHeight = DisplayUtils.dp2px(WZTCardActivity.this, 35);
        gas = DisplayUtils.dp2px(WZTCardActivity.this, 15);

        comment_one = (RelativeLayout) findViewById(R.id.comment_one);
        comment_one_header = (ImageView) findViewById(R.id.comment_one_header);
        comment_one_text = (TextView) findViewById(R.id.comment_one_text);

        comment_two = (RelativeLayout) findViewById(R.id.comment_two);
        comment_two_header = (ImageView) findViewById(R.id.comment_two_header);
        comment_two_text = (TextView) findViewById(R.id.comment_two_text);

        comment_three = (RelativeLayout) findViewById(R.id.comment_three);
        comment_three_header = (ImageView) findViewById(R.id.comment_three_header);
        comment_three_text = (TextView) findViewById(R.id.comment_three_text);

        comment_one.setClickable(true);
        comment_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commentClick(view);
            }
        });

        comment_two.setClickable(true);
        comment_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commentClick(view);
            }
        });

        comment_three.setClickable(true);
        comment_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commentClick(view);
            }
        });

        mHandler = new MyHandler(WZTCardActivity.this);

    }

    private void commentClick(View view){
        DryCommentModel model = null;
        if (dataList != null && dataList.size() > 0){
            if (view.getVisibility() == View.VISIBLE && view.getBackground().getAlpha() >= 255){
                if (view.getTop() == bottomY-2*gas-2*layoutHeight){
                    if (a != null){
                        model = a;
                    }else if (b != null){
                        model = b;
                    }
                }else if (view.getTop() == bottomY-gas-layoutHeight){
                    if (dataList.size() == 1){
                        if (a != null){
                            model = a;
                        }else if (b != null){
                            model = b;
                        }
                    }else {
                        if (b != null){
                            model = b;
                        }else if (a != null){
                            model = a;
                        }
                    }

                }
                if (model != null){
                    Intent intent = new Intent(WZTCardActivity.this, LangCommentActivity.class);
                    intent.putExtra("id",model.getSourceid());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DryCommentModel", model);
                    intent.putExtras(bundle);
                    intent.putExtra("isReply",false);
                    intent.putExtra("type",1);
                    startActivity(intent);
                }
            }
        }
    }

    private void resetMoveComment(){


        WidgetController.setLayout(comment_one,gas,bottomY-2*gas-2*layoutHeight);

        WidgetController.setLayout(comment_two, gas, bottomY-gas-layoutHeight);

        WidgetController.setLayout(comment_three, gas, bottomY);

        comment_one.setVisibility(View.INVISIBLE);
        comment_two.setVisibility(View.INVISIBLE);
        comment_three.setVisibility(View.INVISIBLE);

        isFirstMove = true;

    }


    private void getComment(int index){

        if (WZTCardActivity.this == null){
            return;
        }

        if (adapter == null || adapter.list == null || adapter.list.size() == 0 || index >= adapter.list.size()){
            return;
        }

        final WeiShuContentDetailModel wc = adapter.list.get(index);

        if (dataIndexMap.containsKey(CommentdbModel.getDataId(wc.getLangid())) == false){
            dataIndexMap.put(CommentdbModel.getDataId(wc.getLangid()), ""+index);
        }

        if (wc.getCommentcount() < 1){
            if (viewPager.getCurrentItem() == index){
                dataList.clear();
                comment_one.setVisibility(View.INVISIBLE);
                comment_two.setVisibility(View.INVISIBLE);
                comment_three.setVisibility(View.INVISIBLE);
            }
        }

        if (dataMap.containsKey(""+index) == true){//已经获取过数据了
            if (index == viewPager.getCurrentItem()){
                isFirstMove = true;
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        CommentdbModel c = CommentdbService.getData(CommentdbModel.getDataId(wc.getLangid()));
                        if (c != null){
                            final List<DryCommentModel> l = GsonTools.getDryCommentModel1(c.getContent());
                            if (l != null && l.size() > 0){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        dataList.clear();
                                        dataList.addAll(l);
                                        resetMoveComment();
                                        displayComment();
                                    }
                                });
                            }
                        }
                    }
                }.start();
            }
            return;
        }

        if (wc.getCommentcount() < 1){
            dataMap.put(""+index,"1");
            return;
        }

        dataMap.put(""+index,"1");
        loadComment(index, wc.getLangid());
    }


    private void loadComment(int index, String langid){
        new Thread(){
            @Override
            public void run() {
                super.run();
                final Map<String,String> map = new HashMap<String, String>();
                map.put("banner","1");
                map.put("pageIndex","0");
                map.put("pageRecord",CommentdbModel.pageSize);
                if (CommonUtils.isLogin() == true){
                    map.put("token",CustomApplication.loginModel.getToken());
                }
                String url = "weishu/theme/comment/list.do";
                if (langid.length() == 32){//微纸条内容

                }else {//微纸条

                }
                map.put("dataId",langid);

                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<DryCommentModel> l = GsonTools.getDryCommentModel1(data);
                            if (l != null && l.size() > 0){
                                String id = CommentdbModel.getDataId(l.get(0).getSourceid());
                                if (index >= 0){
                                    String k = dataIndexMap.get(id);
                                    if (!CommonUtils.isEmpty(k) && viewPager.getCurrentItem() == Integer.valueOf(k)){
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                dataList.clear();
                                                dataList.addAll(l);
                                                resetMoveComment();
                                                displayComment();
                                            }
                                        });
                                    }
                                }
                                CommentdbModel commentdbModel = new CommentdbModel();
                                commentdbModel.setContent(data);
                                commentdbModel.setSourceid(id);
                                CommentdbService.saveOrUpdate(commentdbModel);
                            }else {
                                CommentdbService.deleteById(CommentdbModel.getDataId(langid));
                            }
                        }else {
                            if (map.containsKey("dataId")){
                                String id = map.get("dataId");
                                if (!CommonUtils.isEmpty(id)){
                                    String k = dataIndexMap.get(CommentdbModel.getDataId(id));
                                    if (!CommonUtils.isEmpty(k)){
                                        dataMap.remove(k);
                                    }

                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (map.containsKey("dataId")){
                            String id = map.get("dataId");
                            if (!CommonUtils.isEmpty(id)){
                                String k = dataIndexMap.get(CommentdbModel.getDataId(id));
                                if (!CommonUtils.isEmpty(k)){
                                    dataMap.remove(k);
                                }

                            }
                        }
                    }
                });
            }
        }.start();
    }

    //检查坐标错乱
    private boolean checkDisplay(){
        if (comment_one.getTop() == comment_two.getTop()
                || comment_one.getTop() == comment_three.getTop()
                || comment_two.getTop() == comment_three.getTop()){
            Log.e("TAG", "坐标错乱了");
            comment_one.setVisibility(View.INVISIBLE);
            comment_two.setVisibility(View.INVISIBLE);
            comment_three.setVisibility(View.INVISIBLE);
            WidgetController.setLayout(comment_one, gas, bottomY-2*gas-2*layoutHeight);
            WidgetController.setLayout(comment_two, gas, bottomY-gas-layoutHeight);
            WidgetController.setLayout(comment_three, gas, bottomY);

            comment_one.setVisibility(View.VISIBLE);
            comment_one.getBackground().setAlpha(255);
            comment_one_text.setTextColor(Color.parseColor("#ffffffff"));
            comment_one_text.setText(a.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);
                }catch (Exception e){
                    LangPublishActivity.uploadError("微纸条页面加载评论报错："+e.getLocalizedMessage());
                }
            }

            if (b != null){
                comment_two.setVisibility(View.VISIBLE);
                comment_two_text.setText(b.getContent().replaceAll("\n",""));
                if (WZTCardActivity.this != null){
                    try {
                        Glide.with(WZTCardActivity.this).load(b.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);
                    }catch (Exception e){
                        LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                    }
                }
                comment_two.getBackground().setAlpha(60);
                comment_two_text.setTextColor(Color.parseColor("#80ffffff"));
            }

            boolean isOpen = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.MoveCommentKey, true);
            if (isOpen == false){
                comment_one.setVisibility(View.INVISIBLE);
                comment_two.setVisibility(View.INVISIBLE);
                comment_three.setVisibility(View.INVISIBLE);
            }

            return true;
        }
        return false;
    }

    public void displayComment(){

        if (WZTCardActivity.this == null){
            return;
        }

        Log.e("TAG", "坐标bottomY="+bottomY);
        Log.e("TAG", "坐标Y="+comment_three.getTop());

        if (dataList == null || dataList.size() == 0){
            resetMoveComment();
            return;
        }

        boolean isOpen = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.MoveCommentKey, true);

        int nowIndex = 0;
        if (displayIndexMap.containsKey(viewPager.getCurrentItem()+"")){
            nowIndex = displayIndexMap.get(viewPager.getCurrentItem()+"");
        }

        if (dataList == null || dataList.size() < 1){
            comment_one.setVisibility(View.INVISIBLE);
            comment_two.setVisibility(View.INVISIBLE);
            comment_three.setVisibility(View.INVISIBLE);
        }else if (dataList.size() == 1){
            comment_one.setVisibility(View.INVISIBLE);

            comment_two.setVisibility(View.VISIBLE);
            WidgetController.setLayout(comment_two,gas,bottomY-gas-layoutHeight);
            comment_two.getBackground().setAlpha(255);
            comment_two_text.setTextColor(Color.parseColor("#ffffffff"));
            a = dataList.get(0);
            comment_two_text.setText(a.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);
                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }

            comment_three.setVisibility(View.INVISIBLE);
        }else if (dataList.size() == 2){
            comment_one.setVisibility(View.VISIBLE);
            WidgetController.setLayout(comment_one,gas,bottomY-2*gas-2*layoutHeight);
            comment_one.getBackground().setAlpha(255);
            comment_one_text.setTextColor(Color.parseColor("#ffffffff"));
            a = dataList.get(0);
            comment_one_text.setText(a.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);

                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }

            comment_two.setVisibility(View.VISIBLE);
            WidgetController.setLayout(comment_two, gas, bottomY-gas-layoutHeight);
            comment_two.getBackground().setAlpha(255);
            comment_two_text.setTextColor(Color.parseColor("#ffffffff"));
            b = dataList.get(1);
            comment_two_text.setText(b.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(b.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);

                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }

            comment_three.setVisibility(View.INVISIBLE);
        }else {

            a = null;
            b = null;
            c = null;

            if (nowIndex >= dataList.size()){
                nowIndex = 0;
            }

            if (dataList.size() - nowIndex == 1){//还有1条内容
                a = dataList.get(nowIndex);
            }else if (dataList.size() - nowIndex == 2){//还有2条内容
                a = dataList.get(nowIndex);
                b = dataList.get(nowIndex+1);
            }else {//还有3条或以上内容
                a = dataList.get(nowIndex);
                b = dataList.get(nowIndex+1);
                c = dataList.get(nowIndex+2);
            }
            nowIndex += 1;
            displayIndexMap.put(viewPager.getCurrentItem()+"",nowIndex);

            if (isFirstMove == true){
                isFirstMove = false;
                comment_one.setVisibility(View.INVISIBLE);
                comment_two.setVisibility(View.INVISIBLE);
                comment_three.setVisibility(View.INVISIBLE);
                WidgetController.setLayout(comment_one, gas, bottomY-2*gas-2*layoutHeight);
                WidgetController.setLayout(comment_two, gas, bottomY-gas-layoutHeight);
                WidgetController.setLayout(comment_three, gas, bottomY);

                comment_one.setVisibility(View.VISIBLE);
                comment_one.getBackground().setAlpha(255);
                comment_one_text.setTextColor(Color.parseColor("#ffffffff"));
                comment_one_text.setText(a.getContent().replaceAll("\n",""));
                if (WZTCardActivity.this != null){
                    try {
                        Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);

                    }catch (Exception e){
                        LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                    }
                }

                if (b != null){
                    comment_two.setVisibility(View.VISIBLE);
                    comment_two_text.setText(b.getContent().replaceAll("\n",""));
                    if (WZTCardActivity.this != null){
                        try {
                            Glide.with(WZTCardActivity.this).load(b.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);

                        }catch (Exception e){
                            LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                        }
                    }

                    comment_two.getBackground().setAlpha(60);
                    comment_two_text.setTextColor(Color.parseColor("#80ffffff"));
                }

            }else {

                //复位
                if (checkDisplay() == true){
                    return;
                }

                if (comment_one.getTop() == bottomY-gas-layoutHeight){//a
                    comment_one.setVisibility(View.VISIBLE);
                    comment_one.getBackground().setAlpha(255);
                    comment_one_text.setTextColor(Color.parseColor("#ffffffff"));
                    comment_one_text.setText(a.getContent().replaceAll("\n",""));
                    if (WZTCardActivity.this != null){
                        try {
                            Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);

                        }catch (Exception e){
                            LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                        }
                    }

                    if (isOpen == false){
                        WidgetController.setLayout(comment_one, gas, bottomY-2*gas-2*layoutHeight);
                    }else {
                        // 以自身为坐标点   参数： x轴的起始点,结束点   y轴的起始点,结束点
                        TranslateAnimation ta = new TranslateAnimation(0,0,0,-gas-layoutHeight);
                        // 设置动画时长
                        ta.setDuration(300);
                        ta.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                comment_one.clearAnimation();
                                WidgetController.setLayout(comment_one, gas, bottomY-2*gas-2*layoutHeight);
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        // 启动动画
                        comment_one.startAnimation(ta);
                    }



                }else if (comment_one.getTop() == bottomY-2*gas-2*layoutHeight){//c
                    WidgetController.setLayout(comment_one, gas, bottomY);
                    comment_one.setVisibility(View.INVISIBLE);
                    if (c != null){
                        comment_one_text.setText(c.getContent().replaceAll("\n",""));
                        if (WZTCardActivity.this != null){
                            try {
                                Glide.with(WZTCardActivity.this).load(c.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);

                            }catch (Exception e){
                                LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                            }
                        }
                    }
                }else {//b
                    if (b != null){
                        comment_one.setVisibility(View.VISIBLE);
                        comment_one_text.setText(b.getContent().replaceAll("\n",""));
                        if (WZTCardActivity.this != null){
                            try {
                                Glide.with(WZTCardActivity.this).load(b.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);

                            }catch (Exception e){
                                LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                            }
                        }
                    }else {
                        comment_one.setVisibility(View.INVISIBLE);
                    }
                    comment_one.getBackground().setAlpha(60);
                    comment_one_text.setTextColor(Color.parseColor("#80ffffff"));
                    WidgetController.setLayout(comment_one, gas, bottomY-gas-layoutHeight);
                }

                if (comment_two.getTop() == bottomY-gas-layoutHeight){//a
                    comment_two.setVisibility(View.VISIBLE);
                    comment_two.getBackground().setAlpha(255);
                    comment_two_text.setTextColor(Color.parseColor("#ffffffff"));
                    comment_two_text.setText(a.getContent().replaceAll("\n",""));
                    if (WZTCardActivity.this != null){
                        try {
                            Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);

                        }catch (Exception e){
                            LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                        }
                    }

                    if (isOpen == false){
                        WidgetController.setLayout(comment_two, gas, bottomY-2*gas-2*layoutHeight);
                    }else {
                        // 以自身为坐标点   参数： x轴的起始点,结束点   y轴的起始点,结束点
                        TranslateAnimation ta = new TranslateAnimation(0,0,0,-gas-layoutHeight);
                        // 设置动画时长
                        ta.setDuration(300);
                        ta.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                comment_two.clearAnimation();
                                WidgetController.setLayout(comment_two, gas, bottomY-2*gas-2*layoutHeight);
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        // 启动动画
                        comment_two.startAnimation(ta);
                    }


                }else if (comment_two.getTop() == bottomY-2*gas-2*layoutHeight){//c
                    WidgetController.setLayout(comment_two, gas, bottomY);
                    comment_two.setVisibility(View.INVISIBLE);
                    if (c != null){
                        comment_two_text.setText(c.getContent().replaceAll("\n",""));
                        if (WZTCardActivity.this != null){
                            try {
                                Glide.with(WZTCardActivity.this).load(c.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);

                            }catch (Exception e){
                                LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                            }
                        }
                    }
                }else {//b
                    if (b != null){
                        comment_two.setVisibility(View.VISIBLE);
                        comment_two_text.setText(b.getContent().replaceAll("\n",""));
                        if (WZTCardActivity.this != null){
                            try {
                                Glide.with(WZTCardActivity.this).load(b.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);

                            }catch (Exception e){
                                LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                            }
                        }
                    }else {
                        comment_two.setVisibility(View.INVISIBLE);
                    }
                    comment_two.getBackground().setAlpha(60);
                    comment_two_text.setTextColor(Color.parseColor("#80ffffff"));
                    WidgetController.setLayout(comment_two, gas, bottomY-gas-layoutHeight);
                }

                if (comment_three.getTop() == bottomY-gas-layoutHeight){//a
                    comment_three.setVisibility(View.VISIBLE);
                    comment_three.getBackground().setAlpha(255);
                    comment_three_text.setTextColor(Color.parseColor("#ffffffff"));
                    comment_three_text.setText(a.getContent().replaceAll("\n",""));
                    if (WZTCardActivity.this != null){
                        try {
                            Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_three_header);

                        }catch (Exception e){
                            LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                        }
                    }

                    if (isOpen == false){
                        WidgetController.setLayout(comment_three, gas, bottomY-2*gas-2*layoutHeight);
                    }else {
                        // 以自身为坐标点   参数： x轴的起始点,结束点   y轴的起始点,结束点
                        //TranslateAnimation ta = new TranslateAnimation(gas,gas,bottomY-gas-layoutHeight,bottomY-2*gas-2*layoutHeight);
                        TranslateAnimation ta = new TranslateAnimation(0,0,0,-gas-layoutHeight);
                        // 设置动画时长
                        ta.setDuration(300);
                        ta.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                comment_three.clearAnimation();
                                WidgetController.setLayout(comment_three, gas, bottomY-2*gas-2*layoutHeight);
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        // 启动动画
                        comment_three.startAnimation(ta);
                    }


                }else if (comment_three.getTop() == bottomY-2*gas-2*layoutHeight){//c
                    WidgetController.setLayout(comment_three, gas, bottomY);
                    comment_three.setVisibility(View.INVISIBLE);
                    if (c != null){
                        comment_three_text.setText(c.getContent().replaceAll("\n",""));
                        if (WZTCardActivity.this != null){
                            try {
                                Glide.with(WZTCardActivity.this).load(c.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_three_header);

                            }catch (Exception e){
                                LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                            }
                        }
                    }
                }else {//b
                    if (b != null){
                        comment_three.setVisibility(View.VISIBLE);
                        comment_three_text.setText(b.getContent().replaceAll("\n",""));
                        if (WZTCardActivity.this != null){
                            try {
                                Glide.with(WZTCardActivity.this).load(b.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_three_header);

                            }catch (Exception e){
                                LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                            }
                        }
                    }else {
                        comment_three.setVisibility(View.INVISIBLE);
                    }
                    comment_three.getBackground().setAlpha(60);
                    comment_three_text.setTextColor(Color.parseColor("#80ffffff"));
                    WidgetController.setLayout(comment_three, gas, bottomY-gas-layoutHeight);
                }
            }

        }

        if (isOpen == false){//动态评论墙已经关闭
            comment_one.setVisibility(View.INVISIBLE);
            comment_two.setVisibility(View.INVISIBLE);
            comment_three.setVisibility(View.INVISIBLE);
        }

    }

    public void writeComment(int position){

        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(WZTCardActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }

        if (adapter != null && adapter.list != null && adapter.list.size() > position){

        }else {
            return;
        }
        WeiShuContentDetailModel wc = adapter.list.get(position);

        if (CommonUtils.bindMobile(WZTCardActivity.this) == true){
            return;
        }

        dialog = new KeyMapDailog("说点什么吧...", new KeyMapDailog.SendBackListener() {
            @Override
            public void sendBack(final String inputText) {
                if (inputText == null || inputText.length() == 0){
                    return;
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //dialog.hideProgressdialog();
                        dialog.dismiss();
                        avi.show();
                        //hintKeyBoard();

                        new Thread(){
                            @Override
                            public void run() {
                                super.run();
                                final HashMap<String, String> map = new HashMap<String, String>();
                                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                                map.put("dataId", wc.getLangid());
                                map.put("dataUserId","");
                                map.put("dataType","0");
                                map.put("dataContent",inputText);
                                map.put("dataAnswerId","0");
                                String url = "weishu/theme/comment.do";
                                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                                    @Override
                                    public void onSuccess(String data) {
                                        Log.e("TAG","评论结果："+data);
                                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                                        if (commonModel.getFlag().equals("1")){
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    avi.hide();
                                                    ToastUtil.show(WZTCardActivity.this, "评论成功");
                                                    DryCommentModel dryCommentModel = new DryCommentModel();
                                                    dryCommentModel.setContent(inputText);
                                                    dryCommentModel.setUserid(CustomApplication.loginModel.getUid());
                                                    dryCommentModel.setHeader(CustomApplication.loginModel.getHeader());
                                                    dryCommentModel.setNickname(CustomApplication.loginModel.getNickname());
                                                    dryCommentModel.setTime(System.currentTimeMillis()+"");
                                                    dryCommentModel.setCcount("0");
                                                    dryCommentModel.setLcount("0");
                                                    dryCommentModel.setIslike("0");
                                                    dryCommentModel.setSharecount("0");
                                                    dryCommentModel.setCollectcount("0");
                                                    dryCommentModel.setIscollect("0");
                                                    dryCommentModel.setType("0");
                                                    dryCommentModel.setSourceid(wc.getLangid());
                                                    dryCommentModel.setCommentid(commonModel.getData()+"");
                                                    double v = Double.valueOf(dryCommentModel.getCommentid());
                                                    int n = (int)v;
                                                    dryCommentModel.setCommentid(n+"");
                                                    Log.e("TAG","评论id"+commonModel.getData());
                                                    dataList.add(0,dryCommentModel);
                                                    displayNewComment(dryCommentModel);
                                                    if (wc.getCommentcount() <= 3){
                                                        displayComment();
                                                    }
                                                    wc.setCommentcount(wc.getCommentcount() + 1);
                                                    adapter.notifyDataSetChanged();
                                                    loadComment(-1, wc.getLangid());//重新加载评论
                                                }
                                            });
                                        }else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    avi.hide();
                                                    ToastUtil.show(WZTCardActivity.this, "提交失败");
                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    public void onError(String msg) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                avi.hide();
                                                ToastUtil.show(WZTCardActivity.this, "提交失败");
                                            }
                                        });
                                    }
                                });
                            }
                        }.start();
                    }
                }, 5);
            }
        });
        dialog.show(getSupportFragmentManager(), "dialog");
    }

    //展示最新的评论
    private void displayNewComment(DryCommentModel model){
        if (model == null){
            return;
        }
        a = model;
        if (comment_one.getTop() == bottomY-2*gas-2*layoutHeight){
            comment_one_text.setText(a.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_one_header);

                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }
        }else if (comment_two.getTop() == bottomY-2*gas-2*layoutHeight){
            comment_two_text.setText(a.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_two_header);

                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }
        }else if (comment_three.getTop() == bottomY-2*gas-2*layoutHeight){
            comment_three_text.setText(a.getContent().replaceAll("\n",""));
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(a.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(comment_three_header);

                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }
        }
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 如果你的app可以横竖屏切换，并且适配4.4或者emui3手机请务必在onConfigurationChanged方法里添加这句话
        ImmersionBar.with(this)
                .statusBarColor(AppThemeUtils.getInstance().getCardThemeColorString())
                .navigationBarColor(AppThemeUtils.getInstance().getMainColorString()) //设置导航栏（虚拟键盘的颜色）
                .hideBar(BarHide.FLAG_SHOW_BAR)
                //.fitsSystemWindows(true)  //使用该属性必须指定状态栏的颜色，不然状态栏透明，很难看
                .init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        ImmersionBar.with(this).destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTimer();
        if(AppUtils.getInstance().isUserAgreeStatus() == false){
            return;
        }
        //JAnalyticsInterface.onPageStart(getApplicationContext(),this.getClass().getCanonicalName());
    }


    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
        if(AppUtils.getInstance().isUserAgreeStatus() == false){
            return;
        }
        //JAnalyticsInterface.onPageEnd(getApplicationContext(),this.getClass().getCanonicalName());
    }

    protected void protectApp() {
//        Intent intent = new Intent(this, MainActivity.class);
//        intent.putExtra(AppUtils.KEY_HOME_ACTION, AppUtils.ACTION_RESTART_APP);
//        startActivity(intent);

        Intent intent = new Intent(this, SplashActivity.class);
        startActivity(intent);
        System.exit(0);
        finish();

//        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);

        //杀掉以前进程
        //android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (AppUtils.getInstance().getAppStatus() == AppUtils.STATUS_FORCE_KILLED){
            //app被系统回收了，重新启动应用
            protectApp();
            return;
        }

        // 所有子类都将继承这些相同的属性,请在设置界面之后设置
        ImmersionBar.with(this)
                .statusBarColor(AppThemeUtils.getInstance().getCardThemeColorString())
                .navigationBarColor(AppThemeUtils.getInstance().getMainColorString()) //设置导航栏（虚拟键盘的颜色）
                .hideBar(BarHide.FLAG_SHOW_BAR)
                //.fitsSystemWindows(true)  //使用该属性必须指定状态栏的颜色，不然状态栏透明，很难看
                .init();

        setContentView(R.layout.activity_wztcard);

        initMoveComment();
        resetMoveComment();

        showLove = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean("showLove", false);
        love_layout = (Love) findViewById(R.id.love_layout);
        love_layout.setBackgroundColor(AppThemeUtils.getInstance().getCardBackgroundColor());
        weiShuInfoDetailModel = (WeiShuInfoDetailModel)getIntent().getSerializableExtra("model");
        music_icon = (ImageView) findViewById(R.id.music_icon);
        if (weiShuInfoDetailModel.getType() == 2 || (CommonUtils.isLogin() == true && weiShuInfoDetailModel.getUserid().equals(CustomApplication.loginModel.getUid()))){
            music_icon.setVisibility(View.VISIBLE);
            music_icon.setClickable(true);
            music_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    enterWZTContentPublishMode();
                }
            });
        }
        TextView card_title = (TextView) findViewById(R.id.card_title);
        card_title.setText(weiShuInfoDetailModel.getTitle());
        RelativeLayout card_title_layout = (RelativeLayout) findViewById(R.id.card_title_layout);
        card_title_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                enterWZTContentMode(0);
            }
        });
        card_page = (TextView) findViewById(R.id.card_page);
        lang_member_icon = (ImageView) findViewById(R.id.lang_member_icon);
        RelativeLayout card_page_layout = (RelativeLayout) findViewById(R.id.card_page_layout);
        card_page_layout.setClickable(true);
        card_page_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wztUser();
            }
        });
        card_page_header = (ImageView) findViewById(R.id.card_page_header);
        card_all_page = (TextView) findViewById(R.id.card_all_page);

        ImageView searchicon = (ImageView) findViewById(R.id.searchicon);
        searchicon.setClickable(true);
        searchicon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (weiShuInfoDetailModel == null){
                    return;
                }
                Intent intent = new Intent(WZTCardActivity.this, WZTContentSearchActivity.class);
                intent.putExtra("id", weiShuInfoDetailModel.getId());
                intent.putExtra("userid", weiShuInfoDetailModel.getUserid());
                intent.putExtra("contentType", weiShuInfoDetailModel.getContentType());
                intent.putExtra("canBrowseAll", weiShuInfoDetailModel.isCanBrowseAll());
                intent.putExtra("needCare", weiShuInfoDetailModel.isNeedCare());
                intent.putExtra("careState", weiShuInfoDetailModel.isCareState());
                intent.putExtra("canPublish", false);
                intent.putExtra("title", weiShuInfoDetailModel.getTitle());
                startActivity(intent);
            }
        });

        isHasMore = true;
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        cardview_bg_img = (ImageView) findViewById(R.id.cardview_bg_img);
        //Glide.with(WZTCardActivity.this).load(R.mipmap.bg_home).apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3))).dontAnimate().into(cardview_bg_img);
        banner_back_layout = (RelativeLayout)findViewById(R.id.banner_back_layout);
        banner_back_layout.setClickable(true);
        banner_back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        banner_more_layout = (RelativeLayout) findViewById(R.id.banner_more_layout);
        banner_more_layout.setClickable(true);
        banner_more_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final List<String> menu = new ArrayList<>();
                if (weiShuInfoDetailModel.isSubscribe() == false){
                    menu.add("订阅微纸条");
                }
                menu.add("分享微纸条");
                if (weiShuInfoDetailModel.getType() == 2){
                    menu.add("发布内容");
                }
                menu.add("发表评论");
                menu.add("作者主页");
                if (weiShuInfoDetailModel.isSubscribe() == true){
                    menu.add("取消订阅");
                }
                menu.add("进入内容模式");
                menu.add("评论墙开关");
                ActionSheetDialog actionSheetDialog = new ActionSheetDialog(WZTCardActivity.this)
                        .builder()
                        .setTitle("请选择")
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true);
                for (String s : menu){
                     actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                         @Override
                         public void onClick(int which) {
                             if (which > 0){
                                 which -= 1;
                                 String title = menu.get(which);
                                 if (title.equals("订阅微纸条") || title.equals("取消订阅")){
                                     subscribe();
                                 } else if (title.equals("发表评论")){
                                     enterWZTContentMode(1);
                                 }else if (title.equals("作者主页")){
                                     wztUser();
                                 }else if (title.equals("进入内容模式")){
                                     enterWZTContentMode(0);
                                 }else if (title.equals("发布内容")){
                                     enterWZTContentPublishMode();
                                 }else if (title.equals("分享微纸条")){
                                     showShare();
                                 }else if (title.equals("评论墙开关")){
                                     showMoveComment();
                                 }
                             }
                         }
                     });
                }
                actionSheetDialog.show();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        adapter = new WZTCardAdapter(this, WZTCardActivity.this, weiShuInfoDetailModel);
        viewPager.setAdapter(adapter);
        viewPager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                48, getResources().getDisplayMetrics()));
        viewPager.setPageTransformer(false, new ScaleTransformer(this));

        //监听ViewPager的跳转状态，当跳转到最后一页时，执行jumpToNext()方法
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            /**
             * 在屏幕滚动过程中不断被调用
             * @param position
             * @param positionOffset   是当前页面滑动比例，如果页面向右翻动，这个值不断变大，最后在趋近1的情况后突变为0。如果页面向左翻动，这个值不断变小，最后变为0
             * @param positionOffsetPixels   是当前页面滑动像素，变化情况和positionOffset一致
             */
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                //Log.e("AAA",isLastPage+"   "+isDragPage+"   "+positionOffsetPixels);
                updatePage();
                if (viewPager.getCurrentItem() >= maxReadCount){
                    if (weiShuInfoDetailModel.isCanBrowseAll() == false){
                        viewPager.setCurrentItem(position);
                        showCare();
                        return;
                    }
                }

                if (adapter != null && adapter.list != null && adapter.list.size() > 0){
                    if (viewPager.getCurrentItem() == adapter.list.size()-1 && hasShowNoMore == false && isHasMore == false){
                        hasShowNoMore = true;
                        ToastUtil.show(WZTCardActivity.this, "亲，我是有底线的哦~");
                    }else {
                        if (adapter.list.size() > 1 && viewPager.getCurrentItem() < adapter.list.size() - 1){
                            hasShowNoMore = false;
                        }
                    }

                    if (viewPager.getCurrentItem() != lastIndex){
                        lastIndex = viewPager.getCurrentItem();
                        getComment(viewPager.getCurrentItem());
                        getComment(viewPager.getCurrentItem()+1);
                        getComment(viewPager.getCurrentItem()+2);
                    }

                }

                if (isHasPic == false)
                {
                    if (adapter != null){
                        if (adapter.list != null && adapter.list.size() > position){
                            WeiShuContentDetailModel model = adapter.list.get(position);
                            if (model.getImglist() != null && model.getImglist().size() > 0){
                                if (WZTCardActivity.this != null){
                                    isHasPic = true;
                                    //Glide.with(WZTCardActivity.this).load(model.getImglist().get(0)).apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3))).dontAnimate().into(cardview_bg_img);
                                }
                            }else {
                                if (WZTCardActivity.this != null){
                                    //Glide.with(WZTCardActivity.this).load(model.getHeader()).apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3))).dontAnimate().into(cardview_bg_img);
                                    //Glide.with(WZTCardActivity.this).load(R.mipmap.bg_home).apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 3))).dontAnimate().into(cardview_bg_img);
                                }

                            }
                        }
                    }

                }

                if (isLastPage && isDragPage){   //当前页是最后一页，并且是拖动状态，并且像素偏移量为0
                    /*
                    if (canJumpPage){
                        canJumpPage = false;
                    }
                    */
                    Log.e("TAG","滑动到最后一页了");
                    getData();
                }

            }

            /**
             * 这个方法有一个参数position，代表哪个页面被选中
             * @param position    当前页的索引
             */
            @Override
            public void onPageSelected(int position) {
                isLastPage = position == adapter.list.size()-3;
                Log.e("TAG","当前页的索引"+position);
            }

            /**
             * 在手指操作屏幕的时候发生变化
             * @param state   有三个值：0（END）,1(PRESS) , 2(UP) 。
             */
            @Override
            public void onPageScrollStateChanged(int state) {

                isDragPage = state == 1;

            }
        });

        getData();

    }

    private void showMoveComment(){

        //夜间模式
        String content = "";
        String tip = "";
        String open = "";
        boolean isOpen = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.MoveCommentKey, true);
        if (isOpen == true){
            isOpen = false;
            content = "亲，应用当前已经开启动态评论墙，是否要关闭？\n（温馨提示：在评论墙所在页面，长按屏幕可以开启或者关闭动态评论墙哦）";
            tip = "动态评论墙已关闭";
            open = "关闭";
        }else {
            isOpen = true;
            content = "亲，应用当前已经关闭动态评论墙，是否要开启？\n（温馨提示：在评论墙所在页面，长按屏幕可以开启或者关闭动态评论墙哦）";
            tip = "动态评论墙已开启";
            open = "开启";
        }
        final boolean openState = isOpen;
        final String tipStr = tip;
        final String openStr = open;
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(WZTCardActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage(content);
        builder.setPositiveButton(openStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.MoveCommentKey, openState);
                displayComment();
                ToastUtil.show(WZTCardActivity.this,tipStr);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    //分享
    public void showShare(){

        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(WZTCardActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }

        if (weiShuInfoDetailModel.getVisible() == false){
            ToastUtil.show(WZTCardActivity.this, "私密微纸条不能分享");
            return;
        }
        if (weiShuInfoDetailModel.getStatus() == 0 || weiShuInfoDetailModel.getStatus() == 2){
            ToastUtil.show(WZTCardActivity.this, "发布内容过少，暂不允许分享。");
            return;
        }

        if (weiShuInfoDetailModel.isNeedAuth() == true){
            if (weiShuInfoDetailModel.getUserid().equals(CustomApplication.loginModel.getUid()) == false){
                ToastUtil.show(WZTCardActivity.this, "授权分类下的微纸条，只有作者才可以分享");
                return;
            }
        }

        Intent intent = new Intent(WZTCardActivity.this, WZTShareActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("model", weiShuInfoDetailModel);//序列化
        intent.putExtras(bundle);//发送数据
        startActivity(intent);

    }

    //更新页面
    private void updatePage(){
        if (totalCount > 0){
            card_all_page.setVisibility(View.VISIBLE);
            if (showLove == false){
                showLove = true;
                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean("showLove", true);
                ToastUtil.show(WZTCardActivity.this, "亲，双击屏幕可以点赞哦~");
                if (love_layout != null){
                    love_layout.addLoveView(ScreenUtils.getScreenWidth(WZTCardActivity.this)/2, ScreenUtils.getScreenHeight(WZTCardActivity.this)/2);
                }
            }
            if (viewPager.getCurrentItem() == 0){
                /*
                if (weiShuInfoDetailModel.getOriginal() == true){
                    card_page.setText("发布作者："+weiShuInfoDetailModel.getNickname());
                }else {
                    card_page.setText("发布者："+weiShuInfoDetailModel.getNickname());
                }
                */
                if (!CommonUtils.isEmpty(weiShuInfoDetailModel.getMemberIcon())){
                    if (WZTCardActivity.this != null){
                        lang_member_icon.setVisibility(View.VISIBLE);
                        try{
                            Glide.with(WZTCardActivity.this).load(weiShuInfoDetailModel.getMemberIcon()).
                                    diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                        }catch (Exception e){
                            LangPublishActivity.uploadError("微纸条卡片加载图片报错："+e.getLocalizedMessage());
                        }
                    }
                }else {
                    lang_member_icon.setVisibility(View.GONE);
                }
                card_page.setText(weiShuInfoDetailModel.getNickname());
                if (WZTCardActivity.this != null){
                    try {
                        Glide.with(WZTCardActivity.this).load(weiShuInfoDetailModel.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(card_page_header);

                    }catch (Exception e){
                        LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                    }
                }
                card_all_page.setText(totalCount+"页");


            }else {
                card_all_page.setText(""+(viewPager.getCurrentItem())+"/"+totalCount);
                WeiShuContentDetailModel m = adapter.list.get(viewPager.getCurrentItem());
                if (!CommonUtils.isEmpty(m.getMemberIcon())){
                    if (WZTCardActivity.this != null){
                        lang_member_icon.setVisibility(View.VISIBLE);
                        try{
                            Glide.with(WZTCardActivity.this).load(m.getMemberIcon()).
                                    diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                        }catch (Exception e){
                            LangPublishActivity.uploadError("微纸条卡片加载图片报错："+e.getLocalizedMessage());
                        }
                    }
                }else {
                    lang_member_icon.setVisibility(View.GONE);
                }
                card_page.setText(m.getNickname());
                if (WZTCardActivity.this != null){
                    try {
                        Glide.with(WZTCardActivity.this).load(m.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(card_page_header);

                    }catch (Exception e){
                        LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                    }
                }
            }

        }else {
            /*
            if (weiShuInfoDetailModel.getOriginal() == true){
                card_page.setText("发布作者："+weiShuInfoDetailModel.getNickname());
            }else {
                card_page.setText("发布者："+weiShuInfoDetailModel.getNickname());
            }
            */
            if (!CommonUtils.isEmpty(weiShuInfoDetailModel.getMemberIcon())){
                if (WZTCardActivity.this != null){
                    lang_member_icon.setVisibility(View.VISIBLE);
                    try{
                        Glide.with(WZTCardActivity.this).load(weiShuInfoDetailModel.getMemberIcon()).
                                diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                    }catch (Exception e){
                        LangPublishActivity.uploadError("微纸条卡片加载图片报错："+e.getLocalizedMessage());
                    }
                }
            }else {
                lang_member_icon.setVisibility(View.GONE);
            }
            card_page.setText(weiShuInfoDetailModel.getNickname());
            if (WZTCardActivity.this != null){
                try {
                    Glide.with(WZTCardActivity.this).load(weiShuInfoDetailModel.getHeader()).transform(new CircleTransform(WZTCardActivity.this)).dontAnimate().into(card_page_header);

                }catch (Exception e){
                    LangPublishActivity.uploadError("加载评论报错："+e.getLocalizedMessage());
                }
            }
            card_all_page.setVisibility(View.INVISIBLE);

        }
    }

    private void showCare(){

        if (isShowCare == true){
            return;
        }
        isShowCare = true;

        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(WZTCardActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("关注作者后才可以查看全部内容，是否现在添加关注？");
        builder.setPositiveButton("关注", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isShowCare = false;
                dialog.dismiss();
                addCare();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isShowCare = false;
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void addCare(){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(WZTCardActivity.this,LoginActivity.class);
            startActivity(intent);
            return;
        }
        if (weiShuInfoDetailModel.isCareState() == false){
            if (weiShuInfoDetailModel.getUserid().equals(CustomApplication.loginModel.getUid())){
                weiShuInfoDetailModel.setCanBrowseAll(true);
                weiShuInfoDetailModel.setCareState(true);
                return;
            }
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", weiShuInfoDetailModel.getUserid());
            String url = "miniapp/"+"langappid"+"/addcare.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                ToastUtil.show(WZTCardActivity.this, "关注成功");
                                weiShuInfoDetailModel.setCareState(true);
                                weiShuInfoDetailModel.setCanBrowseAll(true);
                            }else {
                                ToastUtil.show(WZTCardActivity.this, commonModel.getMsg());
                            }
                        }
                    });

                }

                @Override
                public void onError(String msg) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.show(WZTCardActivity.this, "添加关注失败");
                        }
                    });
                }
            });
        }else {
            weiShuInfoDetailModel.setCanBrowseAll(true);
        }
    }

    //发布作者
    private void wztUser(){

        if (totalCount > 0){
            WeiShuContentDetailModel m = adapter.list.get(viewPager.getCurrentItem());
            Intent intent = new Intent(WZTCardActivity.this, UserLangActivity.class);
            intent.putExtra(APIKey.useridKey,m.getUserid());
            intent.putExtra(APIKey.typeKey,1);
            intent.putExtra(APIKey.titleKey,m.getNickname());
            startActivity(intent);
        }else {
            //进入个人主页
            Intent intent = new Intent(WZTCardActivity.this, UserLangActivity.class);
            intent.putExtra(APIKey.useridKey,weiShuInfoDetailModel.getUserid());
            intent.putExtra(APIKey.typeKey,1);
            intent.putExtra(APIKey.titleKey,weiShuInfoDetailModel.getNickname());
            startActivity(intent);
        }

    }

    //进入微纸条内容模式
    public void enterWZTContentMode(int selectIndex){
        Intent intent = new Intent(WZTCardActivity.this, WZTActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("model", weiShuInfoDetailModel);//序列化
        intent.putExtras(bundle);//发送数据
        intent.putExtra("selectIndex",selectIndex);
        startActivity(intent);
    }

    //进入微纸条发布
    private void enterWZTContentPublishMode(){

        if (bindMobile() == true){
            return;
        }

        Intent intent = new Intent(WZTCardActivity.this, WZTActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("model", weiShuInfoDetailModel);//序列化
        intent.putExtras(bundle);//发送数据
        intent.putExtra("selectIndex",0);
        intent.putExtra("isPublish", true);
        startActivity(intent);
    }

    //绑定手机号
    private boolean bindMobile(){
        if (CommonUtils.isLogin() == true){
            if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
                if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
                    Intent intent = new Intent(WZTCardActivity.this, BDThirdActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
        }
        return false;
    }

    //订阅
    public void subscribe(){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(WZTCardActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("dataId", weiShuInfoDetailModel.getId()+"");
        String url = "weishu/theme/care.do";
        if (weiShuInfoDetailModel.isSubscribe() == true){
            url = "weishu/theme/care/cancel.do";
            weiShuInfoDetailModel.setSubscribe(false);
            if (weiShuInfoDetailModel.getCollectCount() > 0){
                weiShuInfoDetailModel.setCollectCount(weiShuInfoDetailModel.getCollectCount()-1);
            }
        }else {
            weiShuInfoDetailModel.setSubscribe(true);
            weiShuInfoDetailModel.setCollectCount(weiShuInfoDetailModel.getCollectCount()+1);
        }

        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    if (weiShuInfoDetailModel.isSubscribe() == true){
                        ToastUtil.show(WZTCardActivity.this, "订阅成功~");
                    }else {
                        ToastUtil.show(WZTCardActivity.this, "已取消订阅~");
                    }
                }else {
                    //CustomApplication.showTip(commonModel, WZTActivity.this);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void getData(){
        if (isHasMore == false){
            if (isShowNoMore == false){
                isShowNoMore = true;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //ToastUtil.show(WZTCardActivity.this, "亲，已经到底啦~");
                        //ToastUtil.show(WZTCardActivity.this, "亲，我是有底线的哦~");
                    }
                });
            }
            return;
        }
        if (canJumpPage == true){
            return;
        }
        Log.e("TAG","获取数据");
        canJumpPage = true;
        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("dataId",""+weiShuInfoDetailModel.getId());
                map.put("dataType", "0");
                map.put("pageIndex",pageIndex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, "weishu/theme/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<WeiShuContentDetailModel> l = GsonTools.getWeiShuContentDetailModelList(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (l != null && l.size() > 0){
                                        if (pageIndex == 0){
                                            totalCount = GsonTools.getWZTContentCount(data);
                                            updatePage();
                                        }
                                        adapter.list.addAll(l);
                                        adapter.notifyDataSetChanged();
                                        isHasMore = true;
                                        pageIndex += 1;
                                        if (pageIndex == 1){
                                            getComment(0);
                                            getComment(1);
                                            getComment(2);
                                        }
                                    }else {
                                        isHasMore = false;
                                        if (pageIndex == 0){
                                            ToastUtil.show(WZTCardActivity.this, "亲，微纸条暂时还没有内容哦~");
                                        }
                                    }
                                    avi.hide();
                                    canJumpPage = false;
                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    avi.hide();
                                    canJumpPage = false;
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                avi.hide();
                                canJumpPage = false;
                            }
                        });
                    }
                });
            }
        }.start();
    }

}
